import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:get/get.dart';
import 'package:seedfour/app/views/web_screen/screen_params.dart';

import '../../constants.dart';

class WebScreenLogic extends GetxController {
  late InAppWebViewController webViewController;
  var params = Rxn<WebScreenParams>();

  final didiTaxiUrl =
      'https://open.es.xiaojukeji.com/webapp/feESWebapp/callcar/now';
  final didiHotelUrl =
      'https://client.es.xiaojukeji.com/entry/hotel/pages/home/index';
  final didiAirTicketUrl =
      'https://client.es.xiaojukeji.com/entry/flight/pages/home/index';
  final didiTrainTicketUrl =
      'https://client.es.xiaojukeji.com/entry/train/pages/home/index';
  final meiTuanWaiMaiUrl = 'https://sqt.meituan.com/c/waimai/index.html';
  final canYinUrl = 'https://sqt.meituan.com/c/canyin/index.html#/poi-list';
  String cachedUrl = '';
  bool firstTaxi = true;

  @override
  void onInit() {
    params.value = Get.arguments;
    setUrl(params.value?.url ?? '');

    super.onInit();
  }

  void goBack() async {
    print("-" * 20 + "cachedUrl: $cachedUrl");
    bool canGoBack = await webViewController.canGoBack();
    if (canGoBack &&
        cachedUrl != didiTaxiUrl &&
        cachedUrl != didiHotelUrl &&
        cachedUrl != didiAirTicketUrl &&
        cachedUrl != didiTrainTicketUrl &&
        !cachedUrl.contains(canYinUrl) &&
        !(cachedUrl.contains(meiTuanWaiMaiUrl) &&
            cachedUrl.contains("poi/home"))) {
      webViewController.goBack();
    } else {
      Get.back();
    }
  }

  void setWebViewController(InAppWebViewController controller) {
    webViewController = controller;
    webViewController.addJavaScriptHandler(
        handlerName: 'FlutterHandler',
        callback: (args) {
          Get.back(result: args);
        });
  }

  void setTitle(String title) {
    params.update((val) => val?.title = title);
  }

  void setUrl(String url) {
    params.update((val) => val?.url = url);
  }

  void onWebLoaded() {
    if (params.value?.businessType == BusinessType.taxi &&
        cachedUrl != didiTaxiUrl &&
        firstTaxi) {
      firstTaxi = false;
      webViewController.evaluateJavascript(
          source: didiJsScript(BusinessType.taxi));
      return;
    }

    if (params.value?.businessType == BusinessType.trainTicket &&
        cachedUrl != didiTrainTicketUrl) {
      webViewController.evaluateJavascript(
          source: didiJsScript(BusinessType.trainTicket));
      return;
    }

    if (params.value?.businessType == BusinessType.hotel &&
        cachedUrl != didiHotelUrl) {
      webViewController.evaluateJavascript(
          source: didiJsScript(BusinessType.hotel));
      return;
    }

    if (params.value?.businessType == BusinessType.airTicket &&
        cachedUrl != didiAirTicketUrl) {
      webViewController.evaluateJavascript(
          source: didiJsScript(BusinessType.airTicket));
      return;
    }
  }

  String didiJsScript(String businessType) {
    if (businessType == BusinessType.taxi) {
      return """
      (function() {
        let divElement = document.querySelector('.scene-item');
        
        if(divElement) {
          divElement.click();
        }
      })();
      """;
    } else {
      String text = '';
      if (businessType == BusinessType.hotel) {
        text = '酒店';
      } else if (businessType == BusinessType.trainTicket) {
        text = '火车票';
      } else if (businessType == BusinessType.airTicket) {
        text = '机票';
      }

      return """
      (function() {
        let divElements = document.querySelectorAll('.category-title');
            
        divElements.forEach((element) => {
          if(element.textContent.includes('$text')) {
            element.parentElement.click();
            return;
          }
        });
      })();
      """;
    }
  }
}
